package com.itheima.service;

import cn.hutool.core.convert.Convert;
import com.itheima.api.SmsHomeRecommendProductApi;
import com.itheima.exception.ConsumerException;
import com.itheima.pojo.SmsHomeBrand;
import com.itheima.pojo.SmsHomeRecommendProduct;
import com.itheima.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Hakuna Matata
 * @date 2022-10-13-18:36
 */
@Service
public class SmsHomeRecommendProductService {

    @DubboReference
    private SmsHomeRecommendProductApi recommendProductApi;

    //添加首页推荐
    public void recommendProductCreate(SmsHomeRecommendProduct recommendProduct) {
        recommendProductApi.recommendProductCreate(recommendProduct);
    }

    //批量删除
    public void recommendProductDelete(Integer[] ids) {
        //将数组转变成集合, 方便后续操作
        List<Long> idList = Arrays.stream(ids).map(e -> Convert.toLong(e)).collect(Collectors.toList());
        //删除
        if (!recommendProductApi.deleteByIds(idList)) {
            //如果删除失败, 抛出异常
            throw new ConsumerException("删除失败, 请稍后重试!");
        }
    }

    //分页查询推荐品牌
    public PageResult recommendProductList(Integer pageNum, Integer pageSize, String productName, Integer recommendStatus) {
        return recommendProductApi.recommendProductList(pageNum, pageSize, productName, recommendStatus);
    }

    //批量修改状态
    public void updateRecommendStatus(Integer[] ids, Integer recommendStatus) {
        //将数组转变成集合, 方便后续操作
        List<Long> idList = Arrays.stream(ids).map(e -> Convert.toLong(e)).collect(Collectors.toList());
        //调用api修改
        if (!recommendProductApi.updateRecommendStatus(idList, recommendStatus)) {
            //修改失败则抛出异常
            throw new ConsumerException("修改失败, 请稍后重试!");
        }

    }

    //修改排序
    public void updateSortById(Long id, Integer sort) {
        //根据id查询人气推荐实例
        SmsHomeRecommendProduct recommendProduct = recommendProductApi.findById(id);
        if (recommendProduct != null) {
            if (sort != null) {
                recommendProduct.setSort(sort);
            }
        }
        //调用api修改
        recommendProductApi.updateSortById(recommendProduct);
    }
}
